const User = require('../database/UserModel');
const express = require('express');
const multer = require('multer');
const path = require('path');
const jwt = require('jsonwebtoken'); // 加密
const db = require('../database/db'); 

const list = (req, res) => {
    User.list().then(val => res.send({ code: 200, data: val }))
              .catch(err => sendErrorResponse(res, err));
};

const add = (req, res) => {
    User.add(req, res).then(val => res.send({ code: 200, data: val }))
                    .catch(err => sendErrorResponse(res, err));
};

const del = (req, res) => {
    User.del(req, res).then(val => res.send({ code: 200, data: val }))
                    .catch(err => sendErrorResponse(res, err));
};

const pud = (req, res) => {
    User.pud(req, res).then(val => res.send({ code: 200, data: val }))
                    .catch(err => sendErrorResponse(res, err));
};

const login = ({ user, password }) => {
    console.log('查询用户名：' + user + '，密码：' + password);
    const sql = 'SELECT * FROM `sys`.`user` WHERE user=? AND password=? LIMIT 1';
    return executeQuery(sql, [user, password]);
};

const add_user = (req, res) => {
    const sql = 'INSERT INTO `sys`.`user` (`user`, `password`) VALUES (?, ?)';
    executeQuery(sql, [req.body.user, req.body.password], res);
};

const add_list = (req, res) => {
    const sql = 'SELECT * FROM `sys`.`album` LIMIT 0,1000';
    executeQuery(sql, [], res);
};

const add_album = (req, res) => {
    console.log('Received files:', req.files);
    const uploadedFiles = req.files.file;
    const filePaths = handleFileUploads(uploadedFiles);

    console.log('File paths:', filePaths);

    const sql = 'INSERT INTO `sys`.`album` (`title`, `cover`) VALUES (?, ?)';
    executeQuery(sql, [req.body.name, filePaths[0]], res);
};

const del_album = (req, res) => {
    console.log(req.body.id);
    const sql = 'DELETE FROM `sys`.`album` WHERE `id` = ?';
    executeQuery(sql, [req.body.id], res);
};

const pud_album = (req, res) => {
    console.log('Received album id for update:', req.body.id);
    const uploadedFiles = req.files.file;
    const filePaths = handleFileUploads(uploadedFiles);

    console.log('File paths:', filePaths);

    const sql = 'UPDATE `sys`.`album` SET `title` = ?, `cover` = ? WHERE `id` = ?';
    executeQuery(sql, [req.body.name, filePaths[0] || req.body.cover, req.body.id], res);
};

const sel_album = (req, res) => {
    console.log(req.body.id);
    const sql = 'SELECT * FROM `sys`.`img` WHERE `pid` = ?';
    executeQuery(sql, [req.body.id], res);
};

const add_img = (req, res) => {
    console.log('Received files:', req.files);
    const uploadedFiles = req.files.file;
    const filePaths = handleFileUploads(uploadedFiles);

    console.log('File paths:', filePaths);

    if (filePaths.length === 0) {
        return sendErrorResponse(res, new Error('No file paths to save'));
    }

    const sql = 'INSERT INTO `sys`.`img` (`pid`, `img`) VALUES (?, ?)';
    executeQuery(sql, [req.body.id, filePaths[0]], res);
};

const del_img = (req, res) => {
    console.log(req.body.id);
    const sql = 'DELETE FROM `sys`.`img` WHERE `id` = ?';
    executeQuery(sql, [req.body.id], res);
};

const get_app = (req, res) => {
    const sql = 'SELECT * FROM `sys`.`app` LIMIT 0,1000';
    executeQuery(sql, [], res);
};

const add_app = (req, res) => {
    const sql = 'INSERT INTO `sys`.`app` (`user`, `content`) VALUES (?, ?)';
    executeQuery(sql, [req.body.user, req.body.content], res);
};

const del_app = (req, res) => {
    const sql = 'DELETE FROM `sys`.`app` WHERE `id` = ?';
    executeQuery(sql, [req.body.id], res);
};

const get_reply = (req, res) => {
    const sql = 'SELECT * FROM `sys`.`app_reply` LIMIT 0,1000';
    executeQuery(sql, [], res);
};

const add_reply = (req, res) => {
    const sql = 'INSERT INTO `sys`.`app_reply` (`user`, `content`, `pid`) VALUES (?, ?, ?)';
    executeQuery(sql, [req.body.user, req.body.content, req.body.pid], res);
};

const handleFileUploads = (uploadedFiles) => {
    const filePaths = [];
    if (Array.isArray(uploadedFiles)) {
        uploadedFiles.forEach(file => filePaths.push(moveFile(file)));
    } else {
        filePaths.push(moveFile(uploadedFiles));
    }
    return filePaths;
};

const moveFile = (file) => {
    const filePath = `./public/images/${file.name}`;
    file.mv(filePath, err => {
        if (err) throw err;
    });
    return `http://localhost:3000/public/images/${file.name}`;
};

const executeQuery = (sql, params, res) => {
    return new Promise((resolve, reject) => {
        db.query(sql, params, (err, data) => {
            if (err) {
                console.error('Database error:', err);
                reject(err);
            } else {
                console.log('Operation result:', data);
                resolve(data);
            }
        });
    }).then(data => res ? res.send({ code: 200, data }) : data)
      .catch(err => sendErrorResponse(res, err));
};

const sendErrorResponse = (res, err) => {
    res.status(500).send({ code: 500, error: err.message });
};

module.exports = {
    list,
    add,
    del,
    pud,
    login,
    add_user,
    add_list,
    add_album,
    del_album,
    pud_album,
    sel_album,
    add_img,
    del_img,
    get_app,
    add_app,
    del_app,
    get_reply,
    add_reply,
};
